const state = {
    authList: ''
};

function checkAuthInList(str, list){
    for(var i in list){
        if(escape(str) == escape(list[i].name)){
            return true;
        }
    }
    return false;
}

function hasAuth(auth, list){
    let authResult = {};

    for(var i in auth){
        // 某个权限为组合权限[auth_1, auth_2], 需要同时满足
        if(Array.isArray(auth[i])){
            authResult[i] = true;
            for(var k in auth[i]){
                if(!checkAuthInList(auth[i][k], list)){
                    authResult[i] = false;
                    break;
                }
            }
        }else{
            authResult[i] = checkAuthInList(auth[i], list);
        }
    }
    return authResult;
}

const mutations = {
    ['SET_AUTH_LIST'](state, authList) {
        state.authList = authList;
    }
};
const actions = {
    ['CHECK_AUTH']({
        commit,
        state
    }, item) {
        if (state.authList) {
            return Promise.resolve(hasAuth(item, state.authList));
        } else {
            return Promise.reject('需要获取权限列表');
        }
    }
};

export default {
    state,
    mutations,
    actions
};
